package org.rocket.spring.security.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.rocket.spring.security.core.enums.LoginTypeEnum;
import org.rocket.spring.security.core.properties.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author He Peng
 * @create 2018-01-23 22:01
 * @update 2018-01-23 22:01
 * @updatedesc : 更新说明
 * @see
 */

@Component
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    private static final Logger LOG = LoggerFactory.getLogger(MyAuthenticationSuccessHandler.class);

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        LOG.info("Login Failure");

        if (Objects.equals(LoginTypeEnum.JSON , this.securityProperties.getBrowser().getLoginType())) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            Map<String , Object> error = new HashMap<>(1);
            error.put("error" , exception.getMessage());
            response.getWriter().write(this.objectMapper.writeValueAsString(error));
        } else {
            super.onAuthenticationFailure(request , response , exception);
        }
    }
}
